<template>
  <div ref="wrap" class="wrap">
    <div ref="bar" class="bar"></div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

let speed = ref<number>(1)
const bar = ref<HTMLDivElement>()
const wrap = ref<HTMLDivElement>()
const timer = ref<number>(0)

const startLoading = () => {
  let barDom = bar.value as HTMLDivElement
  timer.value = window.requestAnimationFrame(function fn () {
    if (speed.value < 90) {
      speed.value++
      barDom.style.width = speed.value + '%'
      window.requestAnimationFrame(fn)
    } else {
      speed.value = 1
      window.cancelAnimationFrame(timer.value)
    }
  })
}

const endLoading = () => {
  const barDom = bar.value as HTMLDivElement
  const wrapDom = wrap.value as HTMLDivElement

  window.requestAnimationFrame(() => {
    speed.value = 100
    barDom.style.width = speed.value + '%'

    setTimeout(() => {
      wrapDom.style.display = 'none'
      }, 20)
  })
}

defineExpose<{ startLoading: Function, endLoading: Function }>({
  startLoading,
  endLoading
})
</script>

<style scoped lang="scss">
.wrap {
  position: fixed;
  top: 0;
  width: 100%;
  height: 2px;

  .bar {
    height: inherit;
    width: 0;
    background-color: #409EFF;
  }
}
</style>
